package cn.org.timespace.ons.util;

import java.util.Calendar;
import java.util.Random;

public class StringUtil {

	public static boolean isNull(String str) {
		return str == null || str.trim().length() == 0;
	}

	public static boolean notNull(String str) {
		return !isNull(str);
	}

	public static boolean notNull(Object str) {
		if (str == null)
			return false;
		else
			return notNull(str.toString());
	}

	/**
	 * 是否为空
	 * <p>
	 * 如果值=flag也认为是空
	 * 
	 * @author William
	 * @param str
	 * @param flag
	 * @return
	 */
	public static boolean notNull(Object str, String flag) {
		if (str == null || str.toString().trim().length() == 0)
			return false;
		else if (str.toString().trim().equals(flag))
			return false;
		else
			return true;

	}

	public static String cut(String str, int len) {
		int le = str.length();
		return le > len ? str.substring(0, len) : str;
	}

	/**
	 * 根据当前时间生产随机数
	 * 
	 * @return
	 */
	public static String generateRandom() {
		String randomValue = "";
		Random rand = new Random();// 生成随机数
		int random = rand.nextInt();

		Calendar calCurrent = Calendar.getInstance();
		int intDay = calCurrent.get(Calendar.DATE);
		int intMonth = calCurrent.get(Calendar.MONTH) + 1;
		int intYear = calCurrent.get(Calendar.YEAR);
		int intHour = calCurrent.get(Calendar.HOUR_OF_DAY);
		int intMin = calCurrent.get(Calendar.MINUTE);
		int intSecond = calCurrent.get(Calendar.SECOND);
		String now = String.valueOf(intYear) + String.valueOf(intMonth)
				+ String.valueOf(intDay) + String.valueOf(intHour)
				+ String.valueOf(intMin) + String.valueOf(intSecond);

		randomValue = String.valueOf(random > 0 ? random : (-1) * random);
		if (randomValue.length() > 6)
			randomValue = randomValue.substring(0, 6);
		randomValue = now + randomValue;
		return randomValue;
	}
	
	/**
	 * 随机生成指定长度的数字验证码
	 * @param codeLength
	 * @return
	 */
	public static String validateCode(int codeLength){
		char[] codeSequence = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		
		Random random = new Random();
		StringBuffer randomCode = new StringBuffer();
		for (int i = 0; i < codeLength; i++) { 
			String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]); 
			randomCode.append(strRand);
		}
		return randomCode.toString();
	}
}
